package com.pinapel.aixml.models.xml;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import com.pinapel.aixml.models.xml.dom.xsd.SaxPathHandler;
import com.pinapel.aixml.tools.OptionManager;

public class TextModel {
	private String mText = "";
	private String mEncoding = OptionManager.getDefaultEncoding(); 
	
	public TextModel(){
		
	}
	
	public TextModel(String in){
		mText = in;
	}
	public TextModel(String in, String encoding){
		mText = in;
		mEncoding = encoding;
	}
	
	
	public InputStream getInputStream(){
		InputStream res = null;
		try {
			res = new ByteArrayInputStream(mText.getBytes(mEncoding));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		};		
		return res;
	}

	public String getText() {
		return mText;
	}

	public String getEncoding() {
		return mEncoding;
	}

	public void setText(String mText) {
		this.mText = mText;
	}

	public void setEncoding(String mEncoding) {
		this.mEncoding = mEncoding;
	}
	
	public String getXPathFrom(int position) throws ParserConfigurationException, SAXException {
		SAXParserFactory spf = SAXParserFactory.newInstance();
	    spf.setNamespaceAware(true);
	    spf.setValidating(false);
	    
	    // Create a JAXP SAXParser
	    SAXParser saxParser = spf.newSAXParser();

	    // Get the encapsulated SAX XMLReader
	    XMLReader xmlReader = saxParser.getXMLReader();
		
	    // Set the ContentHandler of the XMLReader
	    SaxPathHandler pathHandler = new SaxPathHandler();
	    xmlReader.setContentHandler(pathHandler);
	    
	    try {
	    	InputStream input = new ByteArrayInputStream(mText.substring(0, position).getBytes(mEncoding));
	    	xmlReader.parse(new InputSource(input));
		} catch (IOException e) {
			// TODO Auto-generated catch block
//			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
//			e.printStackTrace();
		}
	    
		return pathHandler.getCurrentXPath();
	}

	
}
